<template>
	<view class="media-picker">

		<!-- <block v-if="isImage(selectedMedia)"> -->
		<image :src="selectedMedia" mode="aspectFill" @click="previewImage"></image>
		<!-- </block> -->
		<view class="actions">
			<button type="default" @click="selectMedia">选择媒体</button>
			<button type="default" @click="clearSelection">清除</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				selectedMedia: '',
				mediaName: '',
				mediaSize: 0
			};
		},
		methods: {
			selectMedia() {
				uni.showActionSheet({
					itemList: ['选择图片', '拍照', '选择文件'],
					success: (res) => {
						if (res.tapIndex === 0) { // 选择图片
							this.selectImage();
						} else if (res.tapIndex === 1) { // 拍照
							this.takePhoto();
						} else if (res.tapIndex === 2) { // 选择文件
							// this.chooseFile();
						}
					}
				});
			},
			selectImage() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						console.log('选择的图片路径:', res.tempFilePaths[0]);
						this.selectedMedia = res.tempFilePaths[0];
					}
				});
			},
			takePhoto() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['camera'],
					success: (res) => {
						this.selectedMedia = res.tempFilePaths[0];
					}
				});
			},
			chooseFile() {
				uni.chooseMessageFile({
					count: 1,
					type: 'file',
					extension: ['pdf', 'ppt', 'pptx'], // 允许选择的文件类型
					success: (res) => {
						const file = res.tempFiles[0];
						this.selectedMedia = file.path;
						this.mediaName = file.name;
						this.mediaSize = Math.round(file.size / 1024); // 文件大小转换为KB
					}
				});
			},
			clearSelection() {
				this.selectedMedia = '';
				this.mediaName = '';
				this.mediaSize = 0;
			},
			isImage(path) {
				const ext = path.split('.').pop().toLowerCase();
				return ['jpg', 'jpeg', 'png', 'bmp', 'gif'].includes(ext);
			},
			previewImage() {
				uni.previewImage({
					urls: [this.selectedMedia]
				});
			}
		}
	}
</script>

<style scoped>
	.media-picker {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.placeholder {
		width: 200px;
		height: 200px;
		border: 1px dashed #ccc;
		text-align: center;
		line-height: 200px;
		cursor: pointer;
	}

	image {
		width: 200px;
		height: 200px;
		margin-bottom: 10px;
	}

	.file-info {
		width: 200px;
		text-align: center;
		margin-bottom: 10px;
	}

	.actions button {
		margin: 5px;
	}
</style>